package me.wangqu.weiyouqu.web.rest.business.dao.impl;

import me.wangqu.weiyouqu.web.rest.business.dao.VideoDao;
import me.wangqu.weiyouqu.web.rest.business.model.BaseModel;
import me.wangqu.weiyouqu.web.rest.business.model.ListModel;
import me.wangqu.weiyouqu.web.rest.util.UrlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by joln on 2016/7/12.
 */
@Repository
public class VideoImpl implements VideoDao {
    private final Logger log = LoggerFactory.getLogger(ArticleImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private ListModel listModels = null;

    @Override
    public ListModel getCodeVideo(Integer code, Integer type, Pageable pageable) {
        if (!ObjectUtils.isEmpty(code)) {
            StringBuffer sql = new StringBuffer(128);
            List<Object> params = new ArrayList<>();
            sql.append("select w.id,w.title,w.day as date,w.pic ,l.link from article w,link l where w.type=? and w.code=? and top>? order by w.day desc,w.id desc limit ?,?");
            params.add(type);
            params.add(code);
            params.add(-1);
            params.add(pageable.getOffset());
            params.add(pageable.getPageSize());
            List<BaseModel> videos = jdbcTemplate.query(sql.toString(), params.toArray(), new RowMapper<BaseModel>() {
                @Override
                public BaseModel mapRow(ResultSet rs, int rowNum) throws SQLException {
                    BaseModel article = new BaseModel();
                    article.setId(rs.getInt("id"));
                    article.setTitle(rs.getString("title"));
                    article.setDate(rs.getString("date"));
                    article.setImg_arr(rs.getString("pic"));
                    String link = rs.getString("link");
                    article.setUrl(UrlUtil.getUrl(link, rs.getString("date"), rs.getInt("id"), type, code));
                    return article;
                }
            });
            return getListModel(videos);
        }

        return null;
    }

    private ListModel getListModel(List<BaseModel> bases) {
        listModels = new ListModel();
        listModels.setLists(bases);
        if (null != bases && !bases.isEmpty()) {
            listModels.setListNums(bases.size());
        }
        return listModels;
    }
}
